package ccnt.pvc.scudwaremobile.activity;

import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.ls.LSInput;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import ccnt.pvc.scudwaremobile.R;
import ccnt.pvc.scudwaremobile.dao.ApkModel;
import ccnt.pvc.scudwaremobile.dao.ServiceModel;
import ccnt.pvc.scudwaremobile.storage.ApkDbManager;
import ccnt.pvc.scudwaremobile.storage.ServiceDbManager;
import ccnt.pvc.scudwaremobile.utils.Constants;
import ccnt.pvc.scudwaremobile.utils.FileUtils;
import ccnt.pvc.scudwaremobile.utils.ThreadPoolUtils;

public class ApkDetialActivity extends Activity implements OnClickListener{

	private final static String TAG = ApkDetialActivity.class.getName();
	private final static int MESSAGE_DOWNLOAD_SUCCESS = 1;
	private final static int MESSAGE_DOWNLOAD_ERROR = 2;
	
	ApkDbManager apkDbManager;
	ServiceDbManager serviceDbManager;
	String packageName;
	ApkModel apkModel;
	String apkPath = null;
	
	TextView textApkInfo;
	Button btnModifyApk;
	ListView listService;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_apkdetial);
		
		packageName = getIntent().getExtras().getString("packageName");
		Log.d(TAG, packageName);
		
		initService();
		initView();
	}
	
	private void initService() {
		apkDbManager = new ApkDbManager(ApkDetialActivity.this);
		serviceDbManager = new ServiceDbManager(ApkDetialActivity.this);
	}
	
	private void initView() {
		apkModel = apkDbManager.getApkByPackageName(packageName);
		
		textApkInfo = (TextView)findViewById(R.id.textApkInfo);
		StringBuilder builder = new StringBuilder();
		builder.append("应用名：" + apkModel.getApkName() + "\n");
		builder.append("包名：" + apkModel.getPackageName() + "\n");
		builder.append("版本：" + apkModel.getVersion() + "\n");
		builder.append("开发者：" + apkModel.getDeveloper());
		textApkInfo.setText(builder.toString());
		
		btnModifyApk = (Button)findViewById(R.id.btnModifyApk);
		btnModifyApk.setText(apkModel.getIsInstalled() == 1 ? "卸载" : "下载并安装");
		btnModifyApk.setOnClickListener(this);
		
		listService = (ListView)findViewById(R.id.listService);
		fillServiceList();
	}
	
	private void fillServiceList() {
		final List<ServiceModel> services = serviceDbManager.getServicesByPackageName(packageName);
		ArrayList<String> serviceNames = new ArrayList<String>();
		for(ServiceModel service : services) {
			serviceNames.add(service.getClassName());
		}
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(
				ApkDetialActivity.this, android.R.layout.simple_list_item_1,
				serviceNames);
		listService.setAdapter(adapter);	
		listService.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				Intent intent = new Intent(ApkDetialActivity.this, ServiceDetailActivity.class);
				intent.putExtra("className", services.get(arg2).getClassName());
				intent.putExtra("isReg", false);
				startActivity(intent);
			}
		});
	}

	@Override
	protected void onRestart() {
		apkModel = apkDbManager.getApkByPackageName(packageName);
		btnModifyApk.setText(apkModel.getIsInstalled() == 1 ? "卸载" : "下载并安装");
		super.onRestart();
	}

	@Override
	public void onClick(View view) {
		int id = view.getId();
		switch(id) {
		case R.id.btnModifyApk:
			if(apkModel.getIsInstalled() == 1) {
				uninstallApk();
			} else {
				ThreadPoolUtils.execute(new Runnable() {
					
					@Override
					public void run() {
						downloadApk();
					}
				});
			}
			break;
		}
	}
	
	/**
	 * 下载APK
	 */
	private void downloadApk() {
		
		String downloadUrl = Constants.SERVER_URL + "/apk/download.do?packageName=" + apkModel.getPackageName();
		Log.d(TAG, "下载地址:" + downloadUrl);
		
		apkPath = FileUtils.downloadFileByUrl(downloadUrl, "scudware/plugins",
				apkModel.getApkName() + System.currentTimeMillis() + ".apk");
		Log.d(TAG, "保存位置:" + apkPath);
		
		if(apkPath == null) {
			apkPath = "/sdcard/scudware/plugins/weixin.apk";
		}
		
		Message message;
		if(apkPath == null) {
			message = handler.obtainMessage(MESSAGE_DOWNLOAD_ERROR);
		} else {
			message = handler.obtainMessage(MESSAGE_DOWNLOAD_SUCCESS);
		}
		message.sendToTarget();
	}
	
	/**
	 * 安装APK
	 */
	private void installApk() {
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setDataAndType(Uri.parse("file://" + apkPath), "application/vnd.android.package-archive");
		i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(i);
	}
	
	/**
	 * 通过包名卸载APK
	 */
	private void uninstallApk() {
		Uri uri = Uri.parse("package:" + packageName);
		Intent intent = new Intent(Intent.ACTION_DELETE, uri);
		startActivity(intent);
	}
	
	private final Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch(msg.what) {
			case MESSAGE_DOWNLOAD_SUCCESS:
				Toast.makeText(ApkDetialActivity.this, "下载成功",
						Toast.LENGTH_SHORT).show();
				installApk();
				break;
			case MESSAGE_DOWNLOAD_ERROR:
				Toast.makeText(ApkDetialActivity.this, "下载失败",
						Toast.LENGTH_SHORT).show();
				break;
			}
		}
		
	};
}
